<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/blog/","images":"/blog/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/blog/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="手动搭建I&#x2F;O网络通信框架1：Socket和ServerSocket入门实战，实现单聊 转载自https:&#x2F;&#x2F;www.cnblogs.com&#x2F;lbhym&#x2F;p&#x2F;12673470.html  前言这个基础项目会作为BIO、NIO、AIO的一个前提，后面会有数篇博客会基于这个小项目利用BIO、NIO、AIO进行改造升级。 简单的说一下io，了解的直接跳过看代码吧:IO常见的使用场景就是网络通信或读取文件">
<meta property="og:type" content="article">
<meta property="og:title" content="手动搭建I&#x2F;O网络通信框架1：Socket和ServerSocket入门实战，实现单聊">
<meta property="og:url" content="http://littlefxc.github.io/2021/05/28/%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI%20O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B61%EF%BC%9ASocket%E5%92%8CServerSocket%E5%85%A5%E9%97%A8%E5%AE%9E%E6%88%98%EF%BC%8C%E5%AE%9E%E7%8E%B0%E5%8D%95%E8%81%8A/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="手动搭建I&#x2F;O网络通信框架1：Socket和ServerSocket入门实战，实现单聊 转载自https:&#x2F;&#x2F;www.cnblogs.com&#x2F;lbhym&#x2F;p&#x2F;12673470.html  前言这个基础项目会作为BIO、NIO、AIO的一个前提，后面会有数篇博客会基于这个小项目利用BIO、NIO、AIO进行改造升级。 简单的说一下io，了解的直接跳过看代码吧:IO常见的使用场景就是网络通信或读取文件">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200410142107890-242008210.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200410142126015-790268014.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200410144802569-1725038127.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200410144811290-2056832827.png">
<meta property="article:published_time" content="2021-05-28T11:39:32.000Z">
<meta property="article:modified_time" content="2021-05-28T01:40:48.148Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="netty">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200410142107890-242008210.png">


<link rel="canonical" href="http://littlefxc.github.io/2021/05/28/%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI%20O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B61%EF%BC%9ASocket%E5%92%8CServerSocket%E5%85%A5%E9%97%A8%E5%AE%9E%E6%88%98%EF%BC%8C%E5%AE%9E%E7%8E%B0%E5%8D%95%E8%81%8A/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>手动搭建I/O网络通信框架1：Socket和ServerSocket入门实战，实现单聊 | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/blog/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/blog/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/blog/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/blog/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/blog/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI-O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B61%EF%BC%9ASocket%E5%92%8CServerSocket%E5%85%A5%E9%97%A8%E5%AE%9E%E6%88%98%EF%BC%8C%E5%AE%9E%E7%8E%B0%E5%8D%95%E8%81%8A"><span class="nav-text">手动搭建I&#x2F;O网络通信框架1：Socket和ServerSocket入门实战，实现单聊</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Socket%E5%92%8CServerSocket%E5%AE%9E%E6%88%98%EF%BC%9A"><span class="nav-text">Socket和ServerSocket实战：</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">184</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">35</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">115</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2021/05/28/%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI%20O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B61%EF%BC%9ASocket%E5%92%8CServerSocket%E5%85%A5%E9%97%A8%E5%AE%9E%E6%88%98%EF%BC%8C%E5%AE%9E%E7%8E%B0%E5%8D%95%E8%81%8A/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          手动搭建I/O网络通信框架1：Socket和ServerSocket入门实战，实现单聊
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2021-05-28 19:39:32 / 修改时间：09:40:48" itemprop="dateCreated datePublished" datetime="2021-05-28T19:39:32+08:00">2021-05-28</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/blog/categories/Netty/" itemprop="url" rel="index"><span itemprop="name">Netty</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="手动搭建I-O网络通信框架1：Socket和ServerSocket入门实战，实现单聊"><a href="#手动搭建I-O网络通信框架1：Socket和ServerSocket入门实战，实现单聊" class="headerlink" title="手动搭建I/O网络通信框架1：Socket和ServerSocket入门实战，实现单聊"></a>手动搭建I/O网络通信框架1：Socket和ServerSocket入门实战，实现单聊</h1><blockquote>
<p>转载自<a target="_blank" rel="noopener" href="https://www.cnblogs.com/lbhym/p/12673470.html">https://www.cnblogs.com/lbhym/p/12673470.html</a></p>
</blockquote>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>这个基础项目会作为BIO、NIO、AIO的一个前提，后面会有数篇博客会基于这个小项目利用BIO、NIO、AIO进行改造升级。</p>
<p>简单的说一下io，了解的直接跳过看代码吧:IO常见的使用场景就是网络通信或读取文件等方面。IO流分为字节流和字符流。字节即Byte，包含八位二进制数，一个二进制数就是1bit，中文名称叫位。字符即一个字母或者一个汉字。一个字母由一个字节组成，而汉字根据编码不同由2个或者3个组成。Java.io包如下:详细的API可自行查阅资料</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200410142107890-242008210.png" alt="https://img2020.cnblogs.com/blog/1383122/202004/1383122-20200410142107890-242008210.png"></p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200410142126015-790268014.png" alt="https://img2020.cnblogs.com/blog/1383122/202004/1383122-20200410142126015-790268014.png"></p>
<p><strong>Socket定义</strong>：套接字（socket）是一个抽象层，应用程序可以通过它发送或接收数据，可对其进行像对文件一样的打开、读写和关闭等操作。套接字允许应用程序将I/O插入到网络中，并与网络中的其他应用程序进行通信。网络套接字是IP地址与端口的组合。</p>
<p><strong>可以理解为两台机器或进程间进行网络通信的端点，这个端点包含IP地址和端口号。</strong></p>
<p>Socket和ServerSocket区别就如其名字一样，简单地说ServerSocket作用在服务端，用以监听客户端的请求。Socket作用在客户端和服务端，用以发送接收消息。但是就像上面说的，它们都要包含一个IP地址和端口号。</p>
<h1 id="Socket和ServerSocket实战："><a href="#Socket和ServerSocket实战：" class="headerlink" title="Socket和ServerSocket实战："></a><strong>Socket和ServerSocket实战：</strong></h1><p>首先创建一个最普通的Java项目。然后创建两个类，Server和Client。其代码和注释如下,仔细看下注释和代码，还是比较简单的</p>
<p>服务器只能为一个客户端服务，一旦监听到客户端的请求，就会一直被这个客户端占用。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Client</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//这是服务端的IP和端口</span></span><br><span class="line">        <span class="keyword">final</span> String DEFAULT_SERVER_HOST = <span class="string">&quot;127.0.0.1&quot;</span>;</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> DEFAULT_SERVER_PORT = <span class="number">8888</span>;</span><br><span class="line">        <span class="comment">//创建Socket</span></span><br><span class="line">        <span class="keyword">try</span> (Socket socket = <span class="keyword">new</span> Socket(DEFAULT_SERVER_HOST, DEFAULT_SERVER_PORT)) &#123;</span><br><span class="line">            <span class="comment">//接收消息</span></span><br><span class="line">            BufferedReader reader = <span class="keyword">new</span> BufferedReader(</span><br><span class="line">                    <span class="keyword">new</span> InputStreamReader(socket.getInputStream())</span><br><span class="line">            );</span><br><span class="line">            <span class="comment">//发送消息</span></span><br><span class="line">            BufferedWriter writer = <span class="keyword">new</span> BufferedWriter(</span><br><span class="line">                    <span class="keyword">new</span> OutputStreamWriter(socket.getOutputStream())</span><br><span class="line">            );</span><br><span class="line">            <span class="comment">//获取用户输入的消息</span></span><br><span class="line">            BufferedReader userReader = <span class="keyword">new</span> BufferedReader(</span><br><span class="line">                    <span class="keyword">new</span> InputStreamReader(System.in)</span><br><span class="line">            );</span><br><span class="line">            String msg = <span class="keyword">null</span>;</span><br><span class="line">            <span class="comment">//循环的话客户端就可以一直输入消息，不然执行完try catch会自动释放资源，也就是断开连接</span></span><br><span class="line">            <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">                String input = userReader.readLine();</span><br><span class="line">                <span class="comment">//写入客户端要发送的消息。因为服务端用readLine获取消息，其以\n为终点，所以要在消息最后加上\n</span></span><br><span class="line">                writer.write(input + <span class="string">&quot;\n&quot;</span>);</span><br><span class="line">                writer.flush();</span><br><span class="line">                msg = reader.readLine();</span><br><span class="line">                System.out.println(msg);</span><br><span class="line">                <span class="comment">//如果客户端输入quit就可以跳出循环、断开连接了</span></span><br><span class="line">                <span class="keyword">if</span>(input.equals(<span class="string">&quot;quit&quot;</span>))&#123;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Server</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> DEFAULT_PORT = <span class="number">8888</span>;</span><br><span class="line">        <span class="comment">//创建ServerSocket监听8888端口</span></span><br><span class="line">        <span class="keyword">try</span> (ServerSocket serverSocket = <span class="keyword">new</span> ServerSocket(DEFAULT_PORT)) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;ServerSocket Start,The Port is:&quot;</span> + DEFAULT_PORT);</span><br><span class="line">            <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;<span class="comment">//不停地监听该端口</span></span><br><span class="line">                <span class="comment">//阻塞式的监听，如果没有客户端请求就一直停留在这里</span></span><br><span class="line">                Socket socket = serverSocket.accept();</span><br><span class="line">                System.out.println(<span class="string">&quot;Client[&quot;</span> + socket.getPort() + <span class="string">&quot;]Online&quot;</span>);</span><br><span class="line">                <span class="comment">//接收消息</span></span><br><span class="line">                BufferedReader reader = <span class="keyword">new</span> BufferedReader(</span><br><span class="line">                        <span class="keyword">new</span> InputStreamReader(socket.getInputStream())</span><br><span class="line">                );</span><br><span class="line">                <span class="comment">//发送消息</span></span><br><span class="line">                BufferedWriter writer = <span class="keyword">new</span> BufferedWriter(</span><br><span class="line">                        <span class="keyword">new</span> OutputStreamWriter(socket.getOutputStream())</span><br><span class="line">                );</span><br><span class="line"></span><br><span class="line">                String msg = <span class="keyword">null</span>;</span><br><span class="line">                <span class="keyword">while</span> ((msg = reader.readLine()) != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    System.out.println(<span class="string">&quot;Client[&quot;</span> + socket.getPort() + <span class="string">&quot;]:&quot;</span> + msg);</span><br><span class="line">                    <span class="comment">//写入服务端要发送的消息</span></span><br><span class="line">                    writer.write(<span class="string">&quot;Server:&quot;</span> + msg + <span class="string">&quot;\n&quot;</span>);</span><br><span class="line">                    writer.flush();</span><br><span class="line">                    <span class="comment">//如果客户端的消息是quit代表他退出了，并跳出循环，不用再接收他的消息了。如果客户端再次连接就会重新上线</span></span><br><span class="line">                    <span class="keyword">if</span> (msg.equals(<span class="string">&quot;quit&quot;</span>)) &#123;</span><br><span class="line">                        System.out.println(<span class="string">&quot;Client[&quot;</span> + socket.getPort() + <span class="string">&quot;]:Offline&quot;</span>);</span><br><span class="line">                        <span class="keyword">break</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后打开两个命令终端，通过javac编译后，一个运行Server代表服务器，一个运行Client代表客户端。</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200410144802569-1725038127.png" alt="https://img2020.cnblogs.com/blog/1383122/202004/1383122-20200410144802569-1725038127.png"></p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/1383122-20200410144811290-2056832827.png" alt="https://img2020.cnblogs.com/blog/1383122/202004/1383122-20200410144811290-2056832827.png"></p>
<p>下一篇 <a href="%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI%20O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B62%EF%BC%9ABIO%E7%BC%96%E7%A8%8B%E6%A8%A1%E5%9E%8B%E5%AE%9E%E7%8E%B0%E7%BE%A4%E8%81%8A%202d2b7fd177844b1ab85c0276e7ae1e7b.md">手动搭建I/O网络通信框架2：BIO编程模型实现群聊</a>  。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/netty/" rel="tag"># netty</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/blog/2021/05/28/%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI%20O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B62%EF%BC%9ABIO%E7%BC%96%E7%A8%8B%E6%A8%A1%E5%9E%8B%E5%AE%9E%E7%8E%B0%E7%BE%A4%E8%81%8A/" rel="prev" title="手动搭建I/O网络通信框架2：BIO编程模型实现群聊">
                  <i class="fa fa-chevron-left"></i> 手动搭建I/O网络通信框架2：BIO编程模型实现群聊
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/blog/2021/05/28/Java%20NIO%E4%B9%8BSelector%EF%BC%88%E9%80%89%E6%8B%A9%E5%99%A8)/" rel="next" title="Java NIO之Selector（选择器）">
                  Java NIO之Selector（选择器） <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/blog/js/utils.js"></script><script src="/blog/js/motion.js"></script><script src="/blog/js/schemes/muse.js"></script><script src="/blog/js/next-boot.js"></script>

  
<script src="/blog/js/local-search.js"></script>






  





</body>
</html>
